package com.chukun.spring.dependency.lookup;


import com.chunkun.ioc.domain.User;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

/**
 * @author chukun
 *
 * 通过ObjectProvider依赖查找
 */
public class ObjectProviderDemo {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册配置类
        applicationContext.register(ObjectProviderDemo.class);
        // 刷新spring的IOC容器
        applicationContext.refresh();
        // 通过beanProvider##getObject依赖查找
        lookupByObjectProvider(applicationContext);
        // 通过beanProvider##getIfAvailable依赖查找
        lookupIfAvailable(applicationContext);
        // 通过beanProvider lambda操作
        lookupByStreamOps(applicationContext);
        // 关闭ioc容器
        applicationContext.close();
    }

    /**
     * java8 lambda 表达式
     * @param applicationContext
     */
    private static void lookupByStreamOps(AnnotationConfigApplicationContext applicationContext) {
        ObjectProvider<String> beanProvider = applicationContext.getBeanProvider(String.class);
        beanProvider.forEach(System.out::println);
    }


    /**
     * getIfAvailable获取对象
     * @param applicationContext
     */
    private static void lookupIfAvailable(AnnotationConfigApplicationContext applicationContext) {
        ObjectProvider<User> beanProvider = applicationContext.getBeanProvider(User.class);
        User availableUser = beanProvider.getIfAvailable(User::createUser);
        System.out.println(availableUser);
    }

    @Bean
    @Primary
    public String helloWorld() {
        return  "Hello,World";
    }

    @Bean
    public String message() {
        return "message";
    }

    private static void lookupByObjectProvider(AnnotationConfigApplicationContext context) {
        ObjectProvider<String> beanProvider = context.getBeanProvider(String.class);
        System.out.println(beanProvider.getObject());
    }
}
